package com.nutiteq.mapper.forms;

import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import com.nutiteq.MapComponent;
import com.nutiteq.components.Place;
import com.nutiteq.mapper.MapScreen;
import com.nutiteq.mapper.Mapper;

public class RemovePlacesList extends List implements CommandListener {

  public static final Command REMOVE_PLACES = new Command("Remove places", Command.ITEM, 0);

  private static final Command BACK = new Command("Back", Command.BACK, 0);
  private static final Command REMOVE = new Command("Remove", Command.ITEM, 0);
  
  private Place[] places;

  private final MapComponent component;
  
  public RemovePlacesList(final Place[] availablePlaces, MapComponent component) {
    super("Places", List.MULTIPLE);
    
    places = availablePlaces;
    this.component = component;
    
    for (int i = 0; i < places.length; i++) {
      append(places[i].getName(), places[i].getIcon());
    }

    addCommand(BACK);
    addCommand(REMOVE);
    setCommandListener(this);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == REMOVE) {
      final Vector removedV = new Vector();
      for (int i = 0; i < size(); i++) {
        if(isSelected(i)) {
          removedV.addElement(places[i]);
        }
      }
      final Place[] removed = new Place[removedV.size()];
      removedV.copyInto(removed);
      component.removePlaces(removed);
    }
    Display.getDisplay(Mapper.instance).setCurrent(MapScreen.instance);
  }
}
